package web;

import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.format.DateTimeFormatter;

import static constant.DateTimeConstant.*;
import static org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type.SERVLET;

@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = SERVLET)
public class WebMvcAutoConfiguration implements WebMvcConfigurer {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        // https://fangshixiang.blog.csdn.net/article/details/89810020
        // 不让 "/hello.aaaa"、"/hello.aaaa/“ 或 "/hello/" 能匹配上 /hello
        // 关闭后缀名匹配，关闭最后一个 / 匹配
        configurer.setUseSuffixPatternMatch(true);
        configurer.setUseTrailingSlashMatch(true);

        // AntPathMatcher pathMatcher = new AntPathMatcher();
        // pathMatcher.setCaseSensitive(false); // URL 忽略大小写
        // configurer.setPathMatcher(pathMatcher);
    }

    /**
     * GET 请求参数中时间类型转换
     * <ul>
     * <li>HH:mm:ss -> LocalTime</li>
     * <li>yyyy-MM-dd -> LocalDate</li>
     * <li>yyyy-MM-dd HH:mm:ss -> LocalDateTime</li>
     * </ul>
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
        registrar.setTimeFormatter(DateTimeFormatter.ofPattern(TIME_FORMAT));
        registrar.setDateFormatter(DateTimeFormatter.ofPattern(DATE_FORMAT));
        registrar.setDateTimeFormatter(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT));
        registrar.registerFormatters(registry);
    }
}